<?php

namespace ApiWF\Controller;

use Common\Controller\ApibaseController;

/**
 * app 首页信息
 */
class HomeController extends ApibaseController
{
    //app 首页信息
    public function index()
    {

        //banner 图片
        $banners = D('Slide')->order('listorder desc')->limit(6)->select();
        foreach ($banners as $key => $ban) {
            $banners[$key]['slide_pic'] = qiniu_mirror_image_url($ban['slide_pic']);
        }

        //资讯
        $posts = D('Posts')->where(['post_status' => 1])->order('post_modified desc')->field('comment_status,post_content_filtered,post_parent,post_mime_type,istop,recommended,post_status,post_author', true)->select();
        foreach ($posts as $key => $value) {
            $posts[$key]['smeta'] = qiniu_mirror_image_url_post($value);
        }

        //活动
        $atcivities = D('ActivityView')->where(['act_status' => ['NEQ', -1]])->order('start_time desc')->select();
        foreach ($atcivities as $key => $act) {
            $atcivities[$key]['act_pic'] = qiniu_mirror_image_url_activity($act);
        }
        //商品
        $goods = D('MerchGoodsView')->where(['goods_status' => 1])->order('update_time desc')->limit(6)->select();
        foreach ($goods as $key => $goo) {
            $goods[$key]['goods_pics'] = qiniu_mirror_image_url_merch_good($goo);
        }

        $data['banners'] = $banners;
        $data['news'] = $posts;
        $data['activities'] = $atcivities;
        $data['goods'] = $goods;

        $this->jsonReturn($data);
    }

    public function index_banner()
    {
        //banner 图片

        $banners = D('Slide')->where(['slide_cid' => 1, 'slide_status' => 1])->field('slide_id,slide_pic,slide_url')->order('listorder desc')->limit(6)->select();
        foreach ($banners as $key => $ban) {
            $banners[$key]['slide_pic'] = qiniu_mirror_image_url($ban['slide_pic']);
            $url = $ban['slide_url'];
            $banners[$key]['parameter_id'] = h5_url_parameter_id($url);
            $banners[$key]['h5_type'] = h5_url_type($url);
        }
        $this->jsonReturn2($banners);
    }

    public function index_news()
    {
        //资讯
        $posts = D('Posts')->where(['post_status' => 1, 'istop' => 1])->order('post_modified desc')->field('comment_status,post_content_filtered,post_parent,post_mime_type,istop,recommended,post_status,post_author,post_content', true)->limit(6)->select();
        foreach ($posts as $key => $value) {
            $posts[$key]['smeta'] = qiniu_mirror_image_url_post($value);
        }
        $this->jsonReturn($posts);
    }

    public function index_act()
    {
        //活动
        $atcivities = D('ActivityView')->where(['Activity.act_status' => 3, 'ActivityCategory.name' => ['like', '%活动%']])->order('start_time desc')->limit(6)->select();
        foreach ($atcivities as $key => $act) {
            $atcivities[$key]['act_pic'] = qiniu_mirror_image_url_activity($act);
        }
        $this->jsonReturn($atcivities);
    }

    public function index_goods()
    {
        //商品
        $goods = D('MerchGoodsView')->where(['MerchGoods.goods_status' => 3])->order('update_time desc')->limit(6)->select();
        foreach ($goods as $key => $goo) {
            $goods[$key]['goods_pics'] = qiniu_mirror_image_url_merch_good($goo);
        }
        $this->jsonReturn($goods);
    }


    //优惠卷橱窗
    //优惠劵详情
    public function couponShopWindow()
    {

        $uid = $this->parseTokenUID();

        $get_coupons = D('UsersCoupon')->where(['uid' => $uid])->field('coupon_id')->select();
        $coupon_ids = array_column($get_coupons, 'coupon_id');
        $where = [
            'coupon_status' => 1,
            '_string' => 'UNIX_TIMESTAMP() < UNIX_TIMESTAMP(end_time)',
        ];

        $coupons = D('Coupon')->where($where)->order('update_time desc')->select();

        foreach ($coupons as $key => $coupon) {
            $coupons[$key]['coupon_pic'] = qiniu_mirror_image_url_coupon($coupon);
            $res = in_array($coupon['id'], $coupon_ids);
            $coupons[$key]['is_get'] = empty($res) ? 0 : 1;
        }
        $this->jsonReturn($coupons);
    }

    public function couponShopWindowPagination()
    {

        $uid = $this->parseTokenUID();

        $get_coupons = D('UsersCoupon')->where(['uid' => $uid])->field('coupon_id')->select();
        $coupon_ids = array_column($get_coupons, 'coupon_id');
        $where = [
            'coupon_status' => 1,
            '_string' => 'UNIX_TIMESTAMP() < UNIX_TIMESTAMP(end_time)',
        ];
        $order = 'update_time desc';
        $model = D('Coupon');

        $data = $this->pageHelper($model, $where, $order);

        $coupons = $data['list'];

        foreach ($coupons as $key => $coupon) {
            $coupons[$key]['coupon_pic'] = qiniu_mirror_image_url_coupon($coupon);
            $res = in_array($coupon['id'], $coupon_ids);
            $coupons[$key]['is_get'] = empty($res) ? 0 : 1;
        }
        $data['list'] = $coupons;
        $this->jsonReturn($data);
    }

    //领取优惠劵
    public function getCoupon()
    {
        $uid = $this->parseTokenUID();
        $coupon_id = I('coupon_id', 0, 'intval');


        $res = D('Coupon')->where(['id'=>$coupon_id,'coupon_status'=>['GT',0]])->find();
        if (empty($res)) {
            $this->error('优惠劵不存在');
        }

        $res = D('UsersCoupon')->where(compact('uid', 'coupon_id'))->find();
        if (!empty($res)) {
            $this->error('优惠劵已经领取');
        }

        $coupon_sn = ($uid % 10000) . date('-si-d');

        $data = [
            'uid' => $uid,
            'coupon_id' => $coupon_id,
            'coupon_sn' => $coupon_sn,
            'coupon_status' => 0,//优惠券状态，0-未使用，1-已使用
            'create_time' => date('Y-m-d')
        ];

        $add_res = D('UsersCoupon')->add($data);

        if ($add_res) {
            //设置消息推送将来时间

            //填写用户消息表
            $coupon_info = D('Coupon')->where(['id' => $coupon_id])->find();
            $expire_time = $coupon_info['end_time'];
            $expire_time_one_day_ago = strtotime($expire_time) - 60 * 60 * 24;
            $expire_time_one_day_ago = date('Y-m-d H:i:s', $expire_time_one_day_ago);
            $coupon_price = $coupon_info['coupon_price'];
            $dataExpire = [
                'uid' => $uid,
                'message_type_id' => 4,
                'title' => '【优惠券过期提醒】',
                'content' => "您有1张价值{$coupon_price}元的优惠券明日到期，快去用掉吧！",
                'coupon_price' => $coupon_price,
                'is_coupon_will_expire' => 1,
                'send_time' => $expire_time_one_day_ago,
                'obj_id' => $add_res,
                'obj_type' => 'coupon',
                'display_type' => 5,//优惠券到期5
            ];

            $start_time_int = strtotime($coupon_info['start_time']);
            $start_time_int_a_day_ago = $start_time_int - 60 * 60 * 24;
            //还有24小时生效
            if ($start_time_int <= time()) {
                //还有24小时生效
                $send_time = date('Y-m-d H:i:s');
                $content = "您有1张价值{$coupon_price}元的优惠券现在就能使用，快去看看吧！";
            } else if ($start_time_int_a_day_ago > time()) {
                $send_time = date('Y-m-d H:i:s', $start_time_int_a_day_ago);
                $content = "您有1张价值{$coupon_price}元的优惠券明日就能使用，快去看看吧！";
            }

            $dataGet = [
                'uid' => $uid,
                'message_type_id' => 4,
                'title' => '【优惠券可用提醒】',
                'content' => $content,
                'coupon_price' => $coupon_price,
                'is_coupon_will_expire' => 0,
                'send_time' => $send_time,
                'obj_id' => $add_res,
                'obj_type' => 'coupon',
                'display_type' => 6,//优惠券可用6
                //  `obj_type` enum('coupon','broadcast','activity','merch','good','news') DEFAULT 'coupon'
            ];
            //产生过期提醒消息
            $user_message_model = M('UserMessages');

            $mg_id_expire = $user_message_model->add($dataExpire);
            //产生获取优惠券消息提醒
            $mg_id_get = $user_message_model->add($dataGet);
            //设置推送 到消息页面统一处理
            $this->success();
        }
        $this->error();
    }

    //废弃
    public function newsDetail()
    {
        //参数
        $id = I('id', 1, 'intval');
        $where = compact('id');
        $where['post_status'] = 1;
        $data = D('Posts')->where($where)->find();
        if (empty($data)) {
            $this->error('资讯不存在');
        }
        $data['smeta'] = qiniu_mirror_image_url_post($data);
        htmlStringToPlainStirngArray($data, 'post_content');
        $this->jsonReturn2($data);
    }

    public function dailyCheckIn()
    {
        $uid = $this->parseTokenUID();

        $check_in_log = D('CheckInLog')->where(['uid' => $uid])->order('check_date desc')->limit(10)->select();
        $total_check_in_days = D('CheckInLog')->where(['uid' => $uid])->Count();


        //判断今天是否签到
        $check_date = date('Y-m-d');
        $is_today_checked_in = D('CheckInLog')->where(compact('uid', 'check_date', 'before_today_continued_checkin_count'))->find();
        if (empty($is_today_checked_in)) {
            $continued_check_in_count = $this->hasAlreadyCheckedInDaysCountBeforeToday($uid);
        } else {
            $continued_check_in_count = intval($is_today_checked_in['continued_checkin_count']);
        }

        //计算超过多少用户
        $outnumber_user_percentage = 0;
        //汇总用户签到记录
        $sql_checkin_count_user_table = "SELECT `uid`,COUNT(1) as check_in_cout FROM `wf_check_in_log` GROUP BY `uid` ORDER BY `check_in_cout` DESC";
        $rank_array = M()->query($sql_checkin_count_user_table);
        $total_number = count($rank_array);
        if ($total_number > 0) {
            foreach ($rank_array as $key => $item) {
                if ($item['uid'] == $uid) {
                    $outnumber_user_percentage = ($total_number - $key) / $total_number * 100;
                    $outnumber_user_percentage = intval($outnumber_user_percentage);
                    break;
                }
            }
        }
        $data = compact('check_in_log', 'continued_check_in_count', 'outnumber_user_percentage');

        //获取用户图像
        $avatar = D('Users')->where(['id' => $uid])->field('avatar,coin')->find();
        $data['avatar'] = qiniu_mirror_image_url($avatar['avatar']);
        $data['user_coin'] = $avatar['coin'];


        //今天是否签到
        $data['is_already_checkin'] = empty($is_today_checked_in) ? 0 : 1;

        $data['total_check_in_days'] = intval($total_check_in_days);
        $this->json_doc = ['total_check_in_days' => '签到天数', 'is_already_checkin' => '1 代表今天已近签到,0代表没有'];
        $this->jsonReturn($data, '签到列表');
    }


    //签到点击
    public function checkInAction()
    {
        $uid = $this->parseTokenUID();
        $check_date = date('Y-m-d');
        $check_time = date('H:m:i');
        $model = D('CheckInLog');

        $log = $model->where(compact('uid', 'check_date'))->find();
        $checkCount = $model->where(compact('uid'))->Count('id');

        $alreayContinuedCheckCount = $this->hasAlreadyCheckedInDaysCountBeforeToday($uid);

        if ($log) {
            $this->success('今天已经签到,请明天再试！签到总次数:' . $checkCount . '已连续签到:' . $alreayContinuedCheckCount . '天');
        } else {

            //写入签到记录
            $gain_coin = ($alreayContinuedCheckCount + 1) * 10;
            $continued_checkin_count = $alreayContinuedCheckCount + 1;
            $data = compact('uid', 'check_date', 'check_time', 'gain_coin', 'continued_checkin_count');
            $res = $model->add($data);

            if ($res) {
                //写入用户金币记录
                $checkCount++;
                //已经签到的次数;
                $alreayContinuedCheckCount++;
                $msg = '签到成功,签到总次数:' . $checkCount . '已近连续签到:' . $alreayContinuedCheckCount . '天';
                //1:金币抽奖 2:金币奖品 3:积分兑换 4:新手任务 5:每日签到 6:金币兑换 7:参加活动 8:退出活动
                $this->addCoinRecord($uid, 5, '签到奖励', $msg, $gain_coin);
                $this->jsonReturn($data, $msg);
            } else {
                $this->error('签到失败' . $model->getError());
            }
        }
    }


    /**
     * @param $uid 用户id
     * @return int|mixed 返回连续签到的天数(今天之前)
     */
    protected function hasAlreadyCheckedInDaysCountBeforeToday($uid)
    {
        //昨天是否签到 且 签到不是第五天
        $check_date = date('Y-m-d', strtotime('yesterday'));
        $continued_checkin_count = ['NEQ', 5];
        $is_yesterday_checked_in = D('CheckInLog')->where(compact('uid', 'check_date', 'continued_checkin_count'))->find();
        if (empty($is_yesterday_checked_in)) {
            $continued_check_in_count = 0;
        } else {
            $continued_check_in_count = $is_yesterday_checked_in['continued_checkin_count'];
        }
        return intval($continued_check_in_count);
    }

    //新手任务

    public function rookieTaskPagination()
    {
        $m = D('ActivityView');
        $where = [
            'ActivityCategory.name' => ['LIKE', '%新手任务%'],
            'Activity.act_status' => ['GT', 0]
        ];
        $order = 'Activity.update_time desc';
        $page_data = $this->pageHelper($m, $where, $order);

        $data = $page_data['list'];

        $uid = $this->parseTokenUID();
        $user_tasks = D('UserTasks')->where(['uid' => $uid])->field('act_id')->select();
        $user_task_ids = array_column($user_tasks, 'act_id');


        $host = C('host',null,'https://api.loogsin.com');

        foreach ($data as $key => $vo) {

            $data[$key]['act_pic'] = qiniu_mirror_image_url_act($vo);
            $task_act_id = $vo['id'];
            $data[$key]['is_done_the_task'] = in_array_case($task_act_id, $user_task_ids) ? 1 : 0;
            htmlStringToPlainStirngArray($data[$key], 'act_content');
            $uri = U('/H5/Web/act',['id'=>$vo['id']]);
            $data[$key]['share_url'] = $host.$uri ;

        }
        //判断用是否是第一次进入
        $is_new = D('Users')->where(['id'=>$uid])->field('is_new')->find();
        if(intval($is_new['is_new'])){
            $page_data['is_new'] = '1';
            D('Users')->where(['id'=>$uid])->save(['is_new'=>0]);
        }else {
            $page_data['is_new'] = '0';
        }
        $page_data['list'] = $data;
        $this->jsonReturn($page_data);
    }


    //点击完成新手任务
    public function doRookieTask()
    {
        $uid = $this->parseTokenUID();
        $act_id = I('task_id', '0', 'intval');
        $where = [
            'ActivityCategory.name' => ['LIKE', '%新手任务%'],
            'Activity.act_status' => ['GT', 0]
        ];
        $res = D('ActivityView')->where($where)->find();
        if(empty($res)){
            $this->error('新手任务不存在');
        }


        $where1 = compact('uid', 'act_id');
        $where1['create_date'] = date('Y-m-d');

        $is_exist = D('UserTasks')->where($where1)->find();
        if (!empty($is_exist)) {
            $this->error('已经完成今天任务');
        } else {
            //奖励金币
            $reward_coin = D('Activity')->where(['id' => $act_id])->field('reward_coin')->find();
            $reward_coin = intval($reward_coin['reward_coin']);

            $data = $where1;
            $data['create_time'] = date('H:i:s');
            D('UserTasks')->add($data);
            //奖励金币
            $discription = '获取金币' . $reward_coin;
            //1:金币抽奖 2:金币奖品 3:积分兑换 4:新手任务 5:每日签到 6:金币兑换 7:参加活动 8:取消参加活动 9:新手任务
            $this->addCoinRecord($uid, 4, '新手任务', $discription, $reward_coin);

            $this->success($discription);
        }

    }


    public function shareNewsDetail(){
        $id = I('id', 0, 'intval');
        $where = compact('id');
        $where['post_status'] = 1;
        $data = D('Posts')->where($where)->field('id,smeta,post_excerpt as content,post_title as title')->find();
        if (empty($data)) {
            $this->error('资讯不存在');
        }
        $data['image'] = qiniu_mirror_image_url_post($data);
        $host = C('host',null,'https://api.loogsin.com');
        $uri = U('/H5/Web/news',['id'=>$id]);
        $data['share_url'] = $host.$uri ;
        unset($data['smeta']);
        $this->jsonReturn2($data);
    }

}

